<template>
  <a-spin :spinning="loading" tip="保存中...">
    <a-form :form="form">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol"
                       label="分类名称">
            <a-input
              v-decorator="['categoryName',{initialValue:category.categoryName, rules: [{ required: true, message: '名称必填，且不能超过20长度' ,max:20}]}]"
              placeholder="请输入分类名称"
              autocomplete="off"/>
          </a-form-item>
        </a-col>

      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item :label-col="{span:4}" :wrapper-col="{span:8,offset:4}">
            <a-button type="primary" @click="handleSubmit">
              <a-icon type="save"/>
              保存
            </a-button>
            <router-link to="/category">
              <a-button type="default">
                <a-icon type="undo"/>
                返回
              </a-button>
            </router-link>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script>
import {findById, saveOrUpdate} from "@/network/category";

const formItemLayout = {
  labelCol: {span: 3},
  wrapperCol: {span: 9}
};
export default {
  name: "CategoryEdit",
  data() {
    return {
      loading: false,
      formItemLayout,
      category: {
        categoryName: null

      }
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this)
  },
  created() {
    let id = this.$route.params.id;
    if (id) {
      findById(id).then(response => {
        this.category = response.data;
      })
    }
  },
  methods: {
    handleSubmit() {
      this.form.validateFields((errors, values) => {
        if (!errors) {
          this.loading = true;
          saveOrUpdate(Object.assign(this.category, this.form.getFieldsValue()))
            .then(response => {
              this.$message.success(response.message);
              this.$router.replace("/category");
            }).catch(response => this.$message.error(response.message))
            .finally(() => this.loading = false);
        }
      });
    }
  }
}
</script>
